//
//  MSAttendanceCardController.m
//  美娱
//
//  Created by No.8 on 2019/4/10.
//  Copyright © 2019 No.8. All rights reserved.
//

#import "MSAttendanceCardController.h"
#import "MSAttendanceCardCell.h"
#import "MSlocationIMGleftButton.h"
#import "DatePickerView.h"
#import "MSAttendDanceCardModel.h"
#define pageSize 15

@interface MSAttendanceCardController ()<UITableViewDelegate,UITableViewDataSource,DatePickerViewDelegate>
//通用导航栏
{
    CustomNavigationBar *naviagtionBar;
    
    NSInteger page;
    
    NSInteger count;
}
@property (nonatomic, strong) DatePickerView *datePickerView;

/** 表视图*/
@property(nonatomic,strong)UITableView *tableView;
/** 遮盖层*/
@property(nonatomic,strong)UIView *backView;


/** 弹出View*/
@property(nonatomic,strong)UIView *showView;


/** 时间*/
@property(nonatomic,strong)UILabel *timelabel;


/** 数组*/
@property(nonatomic,strong)NSMutableArray *CardArray;

/** 模型*/
@property(nonatomic,strong)MSAttendDanceCardModel *AttendDanceCardModel;

@end

@implementation MSAttendanceCardController
/** Nav实现 */
- (int)navBarBottom {
    if ([WRNavigationBar isIphoneX]) {
        return 88;
    } else {
        return 64;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    self.CardArray = [NSMutableArray new];
    
    Prepare *header = [Prepare headerWithRefreshingTarget:self refreshingAction:@selector(MJChiBaoZiHeaderRefresh)];
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    // 马上进入刷新状态
    self.tableView.mj_header = header;
    [self.tableView.header beginRefreshing];
    
}
- (void)MJChiBaoZiHeaderRefresh{
//    page = 1;
     [self ReloaData];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    self.navigationController.navigationBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView * view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    [[UIApplication sharedApplication].keyWindow  addSubview:view];
    self.backView = view;
    view.hidden = YES;
    
    self.datePickerView = [[DatePickerView alloc] initWithFrame:CGRectMake(0, view.height + 235, ScreenWidth, 235) withTimeShowMode:ShowAllTime withIsShowTodayDate:YES];
    self.datePickerView.backgroundColor = [UIColor whiteColor];
    self.datePickerView.delegate = self;
    [view addSubview:self.datePickerView];
    self.datePickerView.hidden = YES;
    
    
    // 单击的 Recognizer(_typeBottomView添加手势)
    UITapGestureRecognizer* singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lightGrayViewSingleTapFromAction)];
    singleRecognizer.numberOfTapsRequired = 1; // 单击
    [self.backView addGestureRecognizer:singleRecognizer];
    
    [self createNavigationBar];
    
    [self CreattableView];
    
    [self CreatView];

}
- (void)ReloaData{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM"];
    NSString *DateTime = [formatter stringFromDate:date];
    
    [self.CardArray removeAllObjects];
    
    NSDictionary * params = @{@"userId":[WYCAccountTool unarchiveuid],@"queryTime":DateTime,@"busId":[WYCAccountTool unarchivebelongBusid]};
    [HTTPRequest POST:MSgetOwnAttendance params:params succeed:^(id responseObject) {
        WYCLog(@"--------%@",responseObject);
        if (CodeStr) {
            [self.tableView.mj_header endRefreshing];
//            count = [responseObject[@"data"][@"count"] integerValue];
            
            
//            NSMutableArray *temporaryArray = [NSMutableArray new];
            for (NSDictionary * dict in responseObject[@"data"]) {
                self.AttendDanceCardModel  = [MSAttendDanceCardModel mj_objectWithKeyValues:dict];
                [self.CardArray addObject:self.AttendDanceCardModel];
//                 = temporaryArray;
            }
            
        }else{
            [self.tableView.mj_header endRefreshing];
            [MBManager showBriefAlert:responseObject[@"msg"]];
//            page = [params[@"page"] integerValue];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
        [MBManager showBriefAlert:Failed];
    }];
}
- (void)FootderRefreshReloadData{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM"];
    NSString *DateTime = [formatter stringFromDate:date];
    
    [self.CardArray removeAllObjects];
    
    NSDictionary * params = @{@"userId":[WYCAccountTool unarchiveuid],@"queryTime":DateTime,@"busId":[WYCAccountTool unarchivebelongBusid],@"page":@(page),@"pageSize":@(pageSize)};
    WYCLog(@"--------%@",params);
    [HTTPRequest POST:MSgetOwnAttendance params:params succeed:^(id responseObject) {
        WYCLog(@"--------%@",responseObject);
        if (CodeStr) {
            [self.tableView.mj_footer endRefreshing];
            
            for (NSDictionary * dict in responseObject[@"data"][@"listMap"]) {
                self.AttendDanceCardModel  = [MSAttendDanceCardModel mj_objectWithKeyValues:dict];
                [self.CardArray addObject:self.AttendDanceCardModel];
            }
            
        }else{
            [self.tableView.mj_footer endRefreshing];
            [MBManager showBriefAlert:responseObject[@"msg"]];
            page --;
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [MBManager showBriefAlert:Failed];
    }];
}
- (void)CreatView{
    UIView * ViewcontrollerView = [[UIView alloc] initWithFrame:CGRectMake(0, [self navBarBottom], ScreenWidth, 200 * px)];
    ViewcontrollerView.backgroundColor = BackViewColor;
    [self.view addSubview:ViewcontrollerView];
    
    
    MSlocationIMGleftButton * locationIMGleftButton = [[MSlocationIMGleftButton alloc] init];
    locationIMGleftButton.frame = CGRectMake(30 * px, 70 * px, 300 * px, 60 * px);
    [locationIMGleftButton setImage:[UIImage imageNamed:@"cqjl_icon"] forState:UIControlStateNormal];
    [locationIMGleftButton setTitle:@"出勤详情" forState:UIControlStateNormal];
    locationIMGleftButton.titleLabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [locationIMGleftButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [ViewcontrollerView addSubview:locationIMGleftButton];
    
    
    /** 时间*/
    UIButton * timeButtonView = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 500 * px, 40 * px, 450 * px, 100 * px)];
    timeButtonView.layer.cornerRadius = 10 * px;//2.0是圆角的弧度，根据需求自己更改
    timeButtonView.layer.borderColor = WYCRGBColor(111, 130, 150).CGColor;//设置边框颜色
    timeButtonView.layer.borderWidth = 1.0f;//设置边框颜色
    [ViewcontrollerView addSubview:timeButtonView];
    
    
    /** */
    UIButton *  timeButton = [[UIButton alloc] initWithFrame:CGRectMake(10 * px, 10 * px, 80 * px, 80 * px)];
    [timeButton setImage:[UIImage imageNamed:@"calendar icon"] forState:UIControlStateNormal];
    [timeButton addTarget:self action:@selector(timeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [timeButtonView addSubview:timeButton];
    
    
    /** */
    UIButton *  previousButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(timeButton.frame) + 20 * px, 10 * px, 40 * px, 80 * px)];
    [previousButton setImage:[UIImage imageNamed:@"日期选择-左箭头"] forState:UIControlStateNormal];
//    [previousButton addTarget:self action:@selector(timeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [timeButtonView addSubview:previousButton];
    
    
    /** 时间*/
    UILabel * timelabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(previousButton.frame) + 20 * px, timeButton.y, 200 * px, timeButton.height)];
    timelabel.textColor = [UIColor grayColor];
    timelabel.text = @"本月";
    timelabel.textAlignment = NSTextAlignmentCenter;
    timelabel.font = [UIFont systemFontOfSize:SYRealValue(28 / 2)];
    [timeButtonView addSubview:timelabel];
    self.timelabel = timelabel;
    
    /** */
    UIButton *  NextButton = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(timelabel.frame) + 20 * px, 10 * px, 40 * px, 80 * px)];
    [NextButton setImage:[UIImage imageNamed:@"日期选择-右箭头"] forState:UIControlStateNormal];
//    [NextButton addTarget:self action:@selector(timeButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [timeButtonView addSubview:NextButton];
    
    
    UIView * HeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(ViewcontrollerView.frame), ScreenWidth, 200 * px)];
    HeaderView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:HeaderView];
    
    /** 日历按钮*/
    UIImageView * PhotoIMG = [[UIImageView alloc] initWithFrame:CGRectMake(30 * px, 25 * px, 150 * px, 150 * px)];
    [PhotoIMG sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[WYCAccountTool unarchiveavatarUrl]]] placeholderImage:[UIImage imageNamed:@"我的头像占位符"]];
    PhotoIMG.layer.cornerRadius = 75 * px;
    PhotoIMG.layer.masksToBounds = YES;
    PhotoIMG.backgroundColor = [UIColor grayColor];
    [HeaderView addSubview:PhotoIMG];
    
    
    /** 名字*/
    UILabel * NameLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(PhotoIMG.frame) + 20 * px, PhotoIMG.y + 45 * px, 500 * px, 60 * px)];
    NameLabel.textColor = [UIColor whiteColor];
    NameLabel.text = [NSString stringWithFormat:@"%@(%@)",[WYCAccountTool unarchiveuserName],[WYCAccountTool unarchiveroleName]];
    NameLabel.textAlignment = NSTextAlignmentLeft;
    NameLabel.font = [UIFont boldSystemFontOfSize:SYRealValue(30 / 2)];
    [HeaderView addSubview:NameLabel];
    self.tableView.tableHeaderView = HeaderView;
    
    
}
/** 表视图*/
- (void)CreattableView{
    if (@available(iOS 11.0, *)) {
        
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = NO;
        
    }
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, [self navBarBottom] + 180 * px, ScreenWidth, ScreenHeight - [self navBarBottom] - 180 * px) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
//    self.tableView.scrollEnabled = NO;
    [self.view addSubview:self.tableView];
    //    }
    //    return _tableView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.CardArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200 * px;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    
    MSAttendanceCardCell * cell = [MSAttendanceCardCell cellWithTableView:tableView];
    tableView.backgroundColor = [UIColor clearColor];
    if (self.CardArray.count > indexPath.row) {
        cell.AttendDanceCardModel = self.CardArray[indexPath.row];
    }
    //无色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.row == 0) {
        cell.topLineView.hidden = YES;
    }
    
    return cell;
}
- (void)createNavigationBar{
    
    self.view.backgroundColor = backgroundcolor;
    naviagtionBar = [[CustomNavigationBar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, [self navBarBottom])];
    [self.view addSubview:naviagtionBar];
    naviagtionBar.titleLabel.text = @"考勤打卡";
    naviagtionBar.backgroundColor = BackViewColor;
    naviagtionBar.rightBtn.hidden = YES;
    naviagtionBar.rightBtnTitle.hidden = YES;
    [self.view addSubview:naviagtionBar];
    
    [naviagtionBar.leftBtn setImage:[UIImage imageNamed:@"左箭头"] forState:UIControlStateNormal];
    [naviagtionBar.leftBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)backClick{
    
    [self.navigationController popViewControllerAnimated:NO];
}
- (void)timeButtonClick{
    self.datePickerView.hidden = NO;
    __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:0.3 // 动画时长
                          delay:0.0 // 动画延迟
                        options:UIViewAnimationOptionCurveEaseIn // 动画过渡效果
                     animations:^{
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.datePickerView.frame = CGRectMake(0, ScreenHeight - 235, ScreenWidth, 235);
                     }
                     completion:^(BOOL finished) {
                         // 动画完成后执行
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.backView.hidden = NO;
                     }];
    
}


- (void)lightGrayViewSingleTapFromAction {
    __weak typeof (self) weakSelf = self;
    [UIView animateWithDuration:0.3 // 动画时长
                          delay:0.0 // 动画延迟
                        options:UIViewAnimationOptionCurveEaseIn // 动画过渡效果
                     animations:^{
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.backView.hidden = YES;
                         strongSelf.datePickerView.frame = CGRectMake(0, ScreenHeight + 235, ScreenWidth, 235);
                     }
                     completion:^(BOOL finished) {
                         // 动画完成后执行
                         __strong typeof (weakSelf) strongSelf = weakSelf;
                         strongSelf.datePickerView.hidden = YES;
                     }];
    
}

#pragma mark - DatePickerViewDelegate
- (void)DatePickerView:(NSString *)year withMonth:(NSString *)month withDay:(NSString *)day withDate:(NSString *)date withTag:(NSInteger)tag{
    
    NSDate  * timedate = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"MM"];
    NSString *DateTime = [formatter stringFromDate:timedate];
    
    //确定
    if (tag == 1001) {
        
        if ([DateTime isEqualToString:month]) {
            self.timelabel.text = @"本月";
        }else{
            self.timelabel.text = date;
        }
        
        [self lightGrayViewSingleTapFromAction];
        
        
        NSDictionary * params = @{@"userId":[WYCAccountTool unarchiveuid],@"queryTime":date,@"busId":[WYCAccountTool unarchivebelongBusid]};
        [HTTPRequest POST:MSgetOwnAttendance params:params succeed:^(id responseObject) {
            if (CodeStr) {
                [self.tableView.mj_header endRefreshing];
                
                for (NSDictionary * dict in responseObject[@"data"]) {
                    self.AttendDanceCardModel  = [MSAttendDanceCardModel mj_objectWithKeyValues:dict];
                    [self.CardArray addObject:self.AttendDanceCardModel];
                }
                
            }else{
                [self.tableView.mj_header endRefreshing];
                [MBManager showBriefAlert:responseObject[@"msg"]];
            }
            [self.tableView reloadData];
        } failure:^(NSError *error) {
            [self.tableView.header endRefreshing];
            [MBManager showBriefAlert:Failed];
        }];
        
        
//        WYCLog(@"--------%@",month);
    }else{//1002：取消
        self.timelabel.text = @"本月";
        [self lightGrayViewSingleTapFromAction];
    }
}
@end
